package cn.finder.datatunnel.protocol;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.log4j.Logger;

import cn.finder.datatunnel.DTConfig;
import cn.finder.datatunnel.ProcessorRunnable;
import cn.finder.datatunnel.processor.Processor;
import cn.finder.datatunnel.processor.TcpDataChannel;

public class Tcp implements Protocol{
	private static Logger logger = Logger.getLogger(Tcp.class);

	private static boolean looper = true;
	private ServerSocket serverSocket = null;
	//private Processor processor;
	
	private Class processorClass;
	public void setProcessorClass(Class processorClass){
		this.processorClass=processorClass;
	}

	public void start() throws Exception{

		serverSocket = new ServerSocket(
				Integer.parseInt(DTConfig.dt_client_listen_port));
		boolean isBound = serverSocket.isBound();
		if (isBound) {
			logger.debug("====socket listening port:"
					+ serverSocket.getLocalPort());
		} else {
			logger.debug("====binding port:" + serverSocket.getLocalPort()
					+ "failure");
			return ;
		}

		while (looper) {

			try {
				Socket socket = serverSocket.accept();// 等待客户端请求

				InetSocketAddress inetAddress = (InetSocketAddress) socket
						.getRemoteSocketAddress();
				logger.debug("==== " + inetAddress.getHostName()
						+ " connected=======");

				try {
					Processor processor=(Processor)processorClass.newInstance();
					TcpDataChannel tcpDataChannel=new TcpDataChannel();
					processor.setDataChannel(tcpDataChannel);
					

					new Thread(new ProcessorRunnable(processor)).start();

				} catch (Exception e) {
					logger.error(e);
				}

			} catch (NumberFormatException e) {
				logger.error(e);
			} catch (IOException e) {
				logger.error(e);
			} finally {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					logger.debug(e);
				}
			}

		}

	}

	public ServerSocket getServerSocket() {
		return serverSocket;
	}


	/*public Processor getProcessor() {
		return processor;
	}

	public void setProcessor(Processor processor) {
		this.processor = processor;
	}*/

	public boolean stop() {
		// TODO Auto-generated method stub
		return false;
	}

	public void destory() {
		// TODO Auto-generated method stub
	}
	
	
	
}
